<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索与添加区域 -- 栅格布局 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索框 -->
          <!-- 利用双向数据绑定完成搜索功能 -->
          <!--
            clearable 显示清空内容按钮
            @clear 该事件会在清除内容后执行(这里绑定为请求数据函数)
          -->
          <el-input
            placeholder="请输入内容"
            v-model="query.query"
            clearable
            @clear="gitUserList"
            true
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="gitUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 添加按钮 -->
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <template>
        <!--
              data 表格数据来源
              stripe 表格隔行变色效果
              border 表格边框
              lable 表头内容
              prop 数据来源
              type="index" 这样写会默认为索引列
        -->
        <el-table :data="userList" stripe border>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="姓名" prop="username"> </el-table-column>
          <el-table-column label="邮箱" prop="email"> </el-table-column>
          <el-table-column label="电话" prop="mobile"> </el-table-column>
          <el-table-column label="角色" prop="role_name"> </el-table-column>
          <el-table-column label="状态" prop="mg_state">
            <!-- 利用作用域插槽 获取数据 -->
            <!-- 可以通过 scope.row 获取到当前列的所有数据 -->
            <template slot-scope="scope">
              <!-- {{ scope.row }} -->
              <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <!-- 通过 id 来操作当前数据行, 通过作用域插槽获取 id -->
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <!--
                type 样式
                icon 图标
                size 尺寸
               -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row)"
              ></el-button>
              <!-- 删除按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserById(scope.row.id)"
              ></el-button>
              <!-- 角色按钮 -->
              <!--
                  <el-tooltip> 文字提示组件
                  enterable 鼠标能否进入提示区域
               -->
              <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="setRightDialog(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 分页区域 -->
      <!--
        @size-change="handleSizeChange" 当每页显示多少条数据发生变化时触发该函数
        @current-change="handleCurrentChange" 当页码值发生变化时触发该函数
      -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户弹出层 -->
    <!-- 头部信息区 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 内容主体区 -->
      <!--
        model 用户数据
        rules 验证规则
        ref 用户数据对象
      -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--  -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户弹出层 -->
    <el-dialog
      title="修改用户数据"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色弹出层 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
    >
      <div>
        <p>当前用户名: {{ userInfo.username }}</p>
        <p>当前角色名: {{ userInfo.role_name }}</p>
        <p>
          选择角色:
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // -------------------自定义验证规则-------------------
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        callback()
      } else {
        callback(new Error('邮箱错误'))
      }
    }
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        callback()
      } else {
        callback(new Error('手机号码错误'))
      }
    }
    return {
      // -------------------定义查询参数-------------------
      query: {
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 2
      },
      userList: [],
      total: 0,
      // -------------------控制添加用户弹出层的显示与隐藏-------------------
      addDialogVisible: false,
      // -------------------添加用户的数据-------------------
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // -------------------添加用户的验证规则-------------------
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }

        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // -------------------控制修改用户弹出层的显示与隐藏-------------------
      editDialogVisible: false,
      // -------------------查询到的用户的数据对象-------------------
      editForm: {},
      // -------------------修改用户的验证规则-------------------
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // -------------------控制分配角色弹出层的显示与隐藏-------------------
      setRoleDialogVisible: false,
      // -------------------当前角色数据-------------------
      userInfo: {},
      // -------------------角色列表-------------------
      roleList: [],
      // -------------------保存分配角色的id-------------------
      selectRoleId: ''

    }
  },
  created () {
    this.gitUserList()
  },
  methods: {
    // -------------------获取用户数据-------------------
    async gitUserList () {
      const { data: res } = await this.$http.get('users', { params: this.query })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // -------------------改变每页多少条数据-------------------
    handleSizeChange (val) {
      this.query.pagesize = val
      this.gitUserList()
    },
    // -------------------改变当前页-------------------
    handleCurrentChange (val) {
      this.query.pagenum = val
      this.gitUserList()
    },
    // -------------------监听 switch 开关状态的改变-------------------
    async userStateChange (row) {
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // -------------------监听添加用户的关闭事件(点击取消重置数据)-------------------
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // -------------------点击确定添加用户-------------------
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status === 201) {
            this.$message.success('添加成功')
            this.gitUserList()
            this.addDialogVisible = false
          } else {
            this.$message.error('添加失败')
          }
        }
      })
    },
    // -------------------根据 id 查询用户信息-------------------
    async showEditDialog (row) {
      const { data: res } = await this.$http.get('users/' + row.id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户数据失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // -------------------监听修改用户的关闭事件(点击取消重置数据)-------------------
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // -------------------点击确定修改用户数据-------------------
    editUser () {
      this.$refs.editFormRef.validate(async (isValid) => {
        if (isValid) {
          const { data: res } = await this.$http.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          if (res.meta.status === 200) {
            this.$message({
              message: '修改成功',
              type: 'success',
              showClose: true,
              duration: 3000
            })
            this.gitUserList()
            this.editDialogVisible = false
          } else {
            this.$message({
              message: '修改失败',
              type: 'error',
              showClose: true,
              duration: 3000
            })
          }
        }
      })
    },
    // -------------------实现删除功能-------------------
    removeUserById (id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        // 点击确定
        await this.$http.delete('users/' + id)
        this.gitUserList()
        this.$message({
          message: '删除成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
      }).catch(() => {
        // 点击取消
      })
    },
    // -------------------获取角色列表,打开弹框功能-------------------
    async setRightDialog (userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    // -------------------实现分配角色功能(点击确定)-------------------
    async setRole () {
      await this.$http.put('users/' + this.userInfo.id + '/role', {
        rid: this.selectRoleId
      })
      this.setRoleDialogVisible = false
      this.gitUserList()
      this.$message({
        message: '分配成功!',
        type: 'success',
        showClose: true,
        duration: 3000
      })
    }
    // -------------------  mouteds end  -------------------
  }
}
</script>

<style>
</style>
